package com.voice.server.controller.device;

import com.voice.server.authentication.TokenAuthentication;
import com.voice.server.entity.Device;
import com.voice.server.input.DeviceQuery;
import com.voice.server.input.DeviceUpdateRequest;
import com.voice.server.output.DeviceInfo;
import com.voice.server.service.DeviceService;
import com.wangjiacai.utils.output.ResultVO;
import com.wangjiacai.utils.utils.ResultVOUtil;
import com.wangjiacai.utils.utils.ValidatorUtil;
import com.wangjiacai.utils.web.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/device/user")
public class DeviceUserController {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RedisService redisService;

    @GetMapping("/num")
    public ResultVO getDeviceListNum(@RequestHeader("token")String token, DeviceQuery deviceQuery, Integer size){
        String userId = (String)redisService.get(token, TokenAuthentication.class).getCredentials();
        deviceQuery.setUserId(userId);
        long totalNum=deviceService.getDeviceListNum(deviceQuery);
        return ResultVOUtil.success((long)Math.ceil(totalNum/(double)size));
    }

    @GetMapping
    public ResultVO getDeviceList(@RequestHeader("token")String token,DeviceQuery deviceQuery, Pageable pageable){
        String userId = (String)redisService.get(token, TokenAuthentication.class).getCredentials();
        deviceQuery.setUserId(userId);
        List<DeviceInfo> list=deviceService.getDeviceList(deviceQuery,pageable);
        return ResultVOUtil.success(list);
    }

    @GetMapping("/{deviceId}")
    public ResultVO getDeviceList(@RequestHeader("token")String token,@PathVariable("deviceId") String deviceId){
        String userId = (String)redisService.get(token, TokenAuthentication.class).getCredentials();
        Device device =deviceService.getDeviceByDeviceIdAndUserId(userId,deviceId);
        return ResultVOUtil.success(device);
    }

    @PutMapping
    public ResultVO postDevice(@RequestHeader("token")String token,@Valid DeviceUpdateRequest deviceUpdateRequest, BindingResult bindingResult){
        String userId = (String)redisService.get(token, TokenAuthentication.class).getCredentials();
        deviceUpdateRequest.setUserId(userId);
        ValidatorUtil.valid(bindingResult);
        deviceService.updateDevice(deviceUpdateRequest);
        return ResultVOUtil.success();
    }


}
